package com.zgw.fireline.base.controls;

import java.util.EventObject;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.zgw.fireline.base.dataset.Dataset;
import com.zgw.fireline.base.dataset.DatasetListener;

public class DataTable extends Table {
	private final Dataset dataset;

	public DataTable(Composite parent, int style, Dataset set) {
		super(parent, style);
		this.dataset = set;
		if (dataset != null) {
			addListener(SWT.Selection, new Listener() {
				public void handleEvent(Event event) {
					Integer index = (Integer) getSelection()[0]
							.getData("DATASET_INDEX");
					if (index != null)
						dataset.setSelected(index);
				}
			});

			final DatasetListener listener = new DatasetListener() {
				public void rowSetChanged(EventObject event) {
					refresh();
				}

				public void rowChanged(EventObject event) {

				}

				public void cursorMoved(EventObject event) {
					if (dataset.getSelectedIndex() == -1) {
						deselectAll();
					} else
						setSelection(dataset.getSelectedIndex()); // DATASET_INDEX
																	// 来查找选择项
				}
			};
			dataset.addDatasetListener(listener);
			addDisposeListener(new DisposeListener() {
				public void widgetDisposed(DisposeEvent e) {
					if (dataset != null)
						dataset.removeDatasetListener(listener);
				}
			});
		}
	}

	@Override
	public void showSelection() {
		super.showSelection();
		Integer index;
		if (dataset != null
				&& (index = (Integer) getSelection()[0]
						.getData("DATASET_INDEX")) != null) {
			dataset.setSelected(index);
		}
	}

	public void refresh() {
		removeAll();
		TableItem item;
		for (int i = 0; i < dataset.getCount(); i++) {
			item = new TableItem(this, SWT.NONE);
			for (TableColumn c : getColumns()) {
				if (c instanceof DataTableColumn) {
					String column = ((DataTableColumn) c).getColumnName();
					DataLabelProvider label = ((DataTableColumn) c)
							.getLabelProvider();
					String value = null;
					if (label == null) {
						value = dataset.getValueForIndex(i, column,
								String.class);
					} else {
						value = label.getText(i, column, dataset);
					}
					item.setText(indexOf(c), value == null ? "" : value);
					item.setData("DATASET_INDEX", i);
				}
			}
			if (i == dataset.getSelectedIndex()) {
				setSelection(item);
			}
		}
	}

	@Override
	protected void checkSubclass() {

	}
}
